package com.github.baichuan.application.scaffold.security;

import com.github.baichuan.application.scaffold.domain.application.Application;
import com.github.baichuan.web.dto.Result;

import java.time.LocalDate;

/**
 * 应用安全策略
 */
public class PasswordSecurityPolicy {
    /**
     * 密码有效天数
     */
    private int validDays;

    /**
     * 密码强度
     */
    private PasswordStrength strength;

    /**
     * 暴力破解保护
     */
    private BruteForceAttackProtection bruteForceAttackProtection;

    public static PasswordSecurityPolicy create(Application application){
        PasswordSecurityPolicy policy = new PasswordSecurityPolicy();
        policy.validDays = application.getPasswordValidDays();
        policy.bruteForceAttackProtection = new BruteForceAttackProtection(application.getPasswordMaxFails(), application.getPasswordLockMinutes());
        return policy;
    }

    /**
     * 密码过期验证
     * @return
     */
    public Result overdue(LocalDate updateDate){
        if(validDays > 0 && updateDate.plusDays(validDays).isBefore(LocalDate.now())){
            return Result.fail("密码已超过" + validDays + "未修改");
        }

        return Result.success("");
    }

    /**
     * 密码强度验证
     * @return
     */
    public Result strength(String password){
        return strength.validate(password);
    }

    /**
     * 密码暴力攻击检测
     */
    public Result attackDetect(String loginName){
        return bruteForceAttackProtection.detect(loginName);
    }

    /**
     * 密码验证失败
     */
    public Result fail(String loginName){
        return bruteForceAttackProtection.failure(loginName);
    }

    /**
     * 密码验证成功
     */
    public Result success(String loginName){
        return bruteForceAttackProtection.success(loginName);
    }
}
